package com.tronsis.distribution.biz.impl;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;

import com.google.gson.reflect.TypeToken;
import com.tronsis.distribution.activity.login.LoginActivity;
import com.tronsis.distribution.activity.login.ResetPasswordActivity;
import com.tronsis.distribution.bean.AddressBean;
import com.tronsis.distribution.bean.NoticeBean;
import com.tronsis.distribution.bean.PayeeMethodBean;
import com.tronsis.distribution.bean.PointsWithdrawBean;
import com.tronsis.distribution.bean.PointsWithdrawLogBean;
import com.tronsis.distribution.bean.RegionHistoryBean;
import com.tronsis.distribution.bean.UserBean;
import com.tronsis.distribution.bean.WithDrawAskBean;
import com.tronsis.distribution.biz.UserBiz;
import com.tronsis.distribution.http.Url;
import com.tronsis.library.db.DBUtil;
import com.tronsis.library.http.HttpCallBack;
import com.tronsis.library.http.ListBean;
import com.tronsis.library.http.RequestClient;
import com.tronsis.library.http.RequestMethod;
import com.tronsis.library.http.UICallBack;
import com.tronsis.library.util.LogUtil;
import com.tronsis.library.util.SharedPreferencesUtil;
import com.tronsis.library.util.StringUtil;

import java.util.List;

import static com.tronsis.library.Constants.SP_HEADER_AUTHORIZATION;

public class UserBizImpl implements UserBiz {

    @Override
    public void login(final Activity activity, String phone, String password, final UICallBack callBack) throws Exception {
        RequestClient.getInstance(new HttpCallBack(activity, UserBean.class) {
            @Override
            public void onStart() {
                callBack.onStart();
            }

            @Override
            public void onCallBack(int status, Object result) {
                switch (status) {
                    case 200:
                        LogUtil.e("user", "请求登录成功");
                        UserBean userBean = (UserBean) result;
                        if (userBean != null) {
                            cacheUserInfo(activity, userBean);
                        } else {
                            LogUtil.e("UserBizImpl", "login 服务器数据返回错误，userbean is null");
                        }
                        callBack.onRefresh(result);
                        break;
                    default:
                        callBack.onFailure(status);
                        break;
                }
            }
        }).addParameter("phone", phone, "password", StringUtil.sha256(password)).excute(RequestMethod.POST, Url.LOGIN_USER);
    }

    @Override
    public void getSmsCode(final Activity activity, String phone, final UICallBack callBack) throws Exception {
        RequestClient.getInstance(new HttpCallBack(activity, UserBean.class) {

            @Override
            public void onStart() {
                callBack.onStart();
            }

            @Override
            public void onCallBack(int status, Object result) {
                switch (status) {
                    case 200:
                        callBack.onRefresh(result);
                        break;
                    default:
                        callBack.onFailure(status);
                        break;
                }
            }
        }).addParameter("phone", phone).excute(RequestMethod.POST, Url.SMS_CODE);
    }

    @Override
    public void register(final Activity activity, String phone, String password, String inviteCode, String smsCode, final UICallBack callBack) throws Exception {
        RequestClient.getInstance(new HttpCallBack(activity, UserBean.class) {
            @Override
            public void onStart() {
                callBack.onStart();
            }

            @Override
            public void onCallBack(int status, Object result) {
                switch (status) {
                    case 200:
                        UserBean userBean = (UserBean) result;
                        if (userBean != null) {
                            cacheUserInfo(activity, userBean);
                        } else {
                            LogUtil.e("UserBizImpl", "login 服务器数据返回错误，userbean is null");
                        }
                        callBack.onRefresh(result);
                        break;
                    default:
                        callBack.onFailure(status);
                        break;
                }
            }
        }).addParameter("phone", phone, "password", StringUtil.sha256(password), "inviteCode", inviteCode, "smsCode", smsCode).excute(RequestMethod.POST, Url.REGISTER);

    }

    @Override
    public void forgetPassword(final Activity activity, String phone, String password, String smsCode, final UICallBack callBack) throws Exception {
        RequestClient.getInstance(new HttpCallBack(activity, String.class) {
            @Override
            public void onStart() {
                callBack.onStart();
            }

            @Override
            public void onCallBack(int status, Object result) {
                switch (status) {
                    case 200:
                        callBack.onRefresh(result);
                        break;
                    default:
                        callBack.onFailure(status);
                        break;
                }
            }
        }).addParameter("phone", phone, "password", StringUtil.sha256(password), "smsCode", smsCode).excute(RequestMethod.POST, Url.FORGET_PASSWORD);
    }

    @Override
    public void updateInfo(Activity activity, boolean appNotice, String avatarFid, String idCardName, String idCardNo, String name, String password, String phone, String region, String wechatId, String wechatVcardFid, final UICallBack callBack) throws Exception {
        RequestClient.getInstance(new HttpCallBack(activity, String.class) {
            @Override
            public void onStart() {
                callBack.onStart();
            }

            @Override
            public void onCallBack(int status, Object result) {
                switch (status) {
                    case 200:
                        callBack.onRefresh(result);
                        break;
                    default:
                        callBack.onFailure(status);
                        break;
                }
            }
        }).addParameter("appNotice", String.valueOf(appNotice), "avatarFid", avatarFid, "idCardName", idCardName, "idCardNo", idCardNo, "name", name, "password", password, "phone", phone, "region", region, "wechatId", wechatId, "wechatVcardFid", wechatVcardFid).excute(RequestMethod.POST, Url.UPDATE_USER);
    }

    @Override
    public void getRegionHistory(Activity activity, final UICallBack callBack) throws Exception {
        RequestClient.getInstance(new HttpCallBack(activity, new TypeToken<List<RegionHistoryBean>>() {
        }.getType()) {
            @Override
            public void onStart() {
                callBack.onStart();
            }

            @Override
            public void onCallBack(int status, Object result) {
                switch (status) {
                    case 200:
                        callBack.onRefresh(result);
                        break;
                    default:
                        callBack.onFailure(status);
                        break;
                }
            }
        }).addParameter().excute(RequestMethod.POST, Url.REGION_HISTORY);
    }

    @Override
    public void getUserInfo(final Activity activity, final UICallBack callBack) throws Exception {
        RequestClient.getInstance(new HttpCallBack(activity, UserBean.class) {

            @Override
            public void onStart() {
                callBack.onStart();
            }

            @Override
            public void onCallBack(int status, Object result) {
                switch (status) {
                    case 200:
                        UserBean userBean = (UserBean) result;
                        if (userBean != null) {
                            cacheUserInfo(activity, userBean);
                        }
                        callBack.onRefresh(result);
                        break;
                    default:
                        callBack.onFailure(status);
                        break;
                }
            }
        }).addGetParams().excute(RequestMethod.GET, Url.UPDATE_USER);
    }

    @Override
    public void getPayeeMethod(Activity activity, final UICallBack callBack) throws Exception {
        RequestClient.getInstance(new HttpCallBack(activity, new TypeToken<List<PayeeMethodBean>>() {
        }.getType()) {

            @Override
            public void onStart() {
                callBack.onStart();
            }

            @Override
            public void onCallBack(int status, Object result) {
                switch (status) {
                    case 200:
                        callBack.onRefresh(result);
                        break;
                    default:
                        callBack.onFailure(status);
                        break;
                }
            }
        }).addGetParams().excute(RequestMethod.GET, Url.PAYEE_METHOD);
    }

    @Override
    public void addPayeeMethod(Activity activity, String account, String bank, String name, final UICallBack callBack) throws Exception {
        RequestClient.getInstance(new HttpCallBack(activity, String.class) {
            @Override
            public void onStart() {
                callBack.onStart();
            }

            @Override
            public void onCallBack(int status, Object result) {
                switch (status) {
                    case 200:
                        callBack.onRefresh(result);
                        break;
                    default:
                        callBack.onFailure(status);
                        break;
                }
            }
        }).addParameter("account", account, "bank", bank, "name", name).excute(RequestMethod.POST, Url.PAYEE_METHOD);
    }

    @Override
    public void updatePayeeMethod(Activity activity, String account, String bank, String name, String payeeId, final UICallBack callBack) throws Exception {
        RequestClient.getInstance(new HttpCallBack(activity, String.class) {
            @Override
            public void onStart() {
                callBack.onStart();
            }

            @Override
            public void onCallBack(int status, Object result) {
                switch (status) {
                    case 200:
                        callBack.onRefresh(result);
                        break;
                    default:
                        callBack.onFailure(status);
                        break;
                }
            }
        }).addParameter("account", account, "bank", bank, "name", name).excute(RequestMethod.POST, String.format("%s%s%s", Url.PAYEE_METHOD, "/", payeeId));
    }

    @Override
    public void deletePayeeMethod(Activity activity, String payeeId, final UICallBack callBack) throws Exception {
        RequestClient.getInstance(new HttpCallBack(activity, String.class) {
            @Override
            public void onStart() {
                callBack.onStart();
            }

            @Override
            public void onCallBack(int status, Object result) {
                switch (status) {
                    case 200:
                        callBack.onRefresh(result);
                        break;
                    default:
                        callBack.onFailure(status);
                        break;
                }
            }
        }).addGetParams().excute(RequestMethod.DELETE, String.format("%s%s%s", Url.PAYEE_METHOD, "/", payeeId));
    }

    @Override
    public void getAddress(Activity activity, final UICallBack callBack) throws Exception {
        RequestClient.getInstance(new HttpCallBack(activity, new TypeToken<List<AddressBean>>() {
        }.getType()) {

            @Override
            public void onStart() {
                callBack.onStart();
            }

            @Override
            public void onCallBack(int status, Object result) {
                switch (status) {
                    case 200:
                        callBack.onRefresh(result);
                        break;
                    default:
                        callBack.onFailure(status);
                        break;
                }
            }
        }).addGetParams().excute(RequestMethod.GET, Url.ADDRESS);
    }

    @Override
    public void addAddress(Activity activity, String detail, String name, String phone, String region, final UICallBack callBack) throws Exception {
        RequestClient.getInstance(new HttpCallBack(activity, String.class) {
            @Override
            public void onStart() {
                callBack.onStart();
            }

            @Override
            public void onCallBack(int status, Object result) {
                switch (status) {
                    case 200:
                        callBack.onRefresh(result);
                        break;
                    default:
                        callBack.onFailure(status);
                        break;
                }
            }
        }).addParameter("detail", detail, "name", name, "phone", phone, "region", region).excute(RequestMethod.POST, String.format("%s", Url.ADDRESS));
    }

    @Override
    public void updateAddress(Activity activity, String addrId, String detail, String name, String phone, String region, final UICallBack callBack) throws Exception {
        RequestClient.getInstance(new HttpCallBack(activity, String.class) {
            @Override
            public void onStart() {
                callBack.onStart();
            }

            @Override
            public void onCallBack(int status, Object result) {
                switch (status) {
                    case 200:
                        callBack.onRefresh(result);
                        break;
                    default:
                        callBack.onFailure(status);
                        break;
                }
            }
        }).addParameter("detail", detail, "name", name, "phone", phone, "region", region).excute(RequestMethod.POST, String.format("%s%s%s", Url.ADDRESS, "/", addrId));
    }

    @Override
    public void deleteAddress(Activity activity, String addrId, final UICallBack callBack) throws Exception {

        RequestClient.getInstance(new HttpCallBack(activity, String.class) {
            @Override
            public void onStart() {
                callBack.onStart();
            }

            @Override
            public void onCallBack(int status, Object result) {
                switch (status) {
                    case 200:
                        callBack.onRefresh(result);
                        break;
                    default:
                        callBack.onFailure(status);
                        break;
                }
            }
        }).addGetParams().excute(RequestMethod.DELETE, String.format("%s%s%s", Url.ADDRESS, "/", addrId));

    }

    @Override
    public void getNotice(Activity activity, Integer page, Integer size, final UICallBack callBack) throws Exception {
        RequestClient.getInstance(new HttpCallBack(activity, new TypeToken<ListBean<NoticeBean>>() {
        }.getType()) {

            @Override
            public void onStart() {
                callBack.onStart();
            }

            @Override
            public void onCallBack(int status, Object result) {
                switch (status) {
                    case 200:
                        callBack.onRefresh(result);
                        break;
                    default:
                        callBack.onFailure(status);
                        break;
                }
            }
        }).addGetParams("page", String.valueOf(page), "size", String.valueOf(size)).excute(RequestMethod.GET, Url.NOTICE);

    }

    @Override
    public void getUnread(Activity activity, final UICallBack callBack) throws Exception {
        RequestClient.getInstance(new HttpCallBack(activity, Integer.class) {

            @Override
            public void onStart() {
                callBack.onStart();
            }

            @Override
            public void onCallBack(int status, Object result) {
                switch (status) {
                    case 200:
                        callBack.onRefresh(result);
                        break;
                    default:
                        callBack.onFailure(status);
                        break;
                }
            }
        }).addGetParams().excute(RequestMethod.GET, Url.UNREAD);
    }

    @Override
    public void getMyPoint(Activity activity, final UICallBack callBack) throws Exception {
        RequestClient.getInstance(new HttpCallBack(activity, Integer.class) {

            @Override
            public void onStart() {
                callBack.onStart();
            }

            @Override
            public void onCallBack(int status, Object result) {
                switch (status) {
                    case 200:
                        callBack.onRefresh(result);
                        break;
                    default:
                        callBack.onFailure(status);
                        break;
                }
            }
        }).addGetParams().excute(RequestMethod.GET, Url.MY_POINTS);
    }


    @Override
    public void cacheUserInfo(Context context, UserBean user) {
        if (user == null) {
            return;
        }

        UserBean loginUser = getLoginUser(context);

        // 在数据库保存用户信息
        if (loginUser == null) {
            DBUtil.getInstance(context).save(user);
        } else {
            if (user.getToken() == null) {
                user.setToken(loginUser.getToken());
            }
            DBUtil.getInstance(context).update(user);
        }

        SharedPreferencesUtil.putString(context, SP_HEADER_AUTHORIZATION, user.getToken());

    }

    @Override
    public UserBean getLoginUser(Context context) {
        List<UserBean> userList = DBUtil.getInstance(context).query(UserBean.class);
        if (userList == null || userList.size() == 0) {
            return null;
        }
        return userList.get(0);
    }

    @Override
    public String getToken(Context context) {
        UserBean user = getLoginUser(context);
        if (user == null) {
            return null;
        }
        return user.getToken();
    }


    @Override
    public String getLoginUserId(Activity context) {
        UserBean user = getLoginUser(context);
        if (user == null) {
            return null;
        }
        return user.getId();
    }

    @Override
    public void logout(Activity context) {
        if (isCurrentActivity(context)) {
            return;
        }

        SharedPreferencesUtil.putString(context, SP_HEADER_AUTHORIZATION, null);
        SharedPreferencesUtil.clear(context);

        DBUtil.getInstance(context).deleteAll(UserBean.class);


        Intent intent = new Intent(context, LoginActivity.class);
        /*
            FLAG_ACTIVITY_CLEAR_TASK 这个标示将在这个活动开始之前清除该栈中所有的任务,将里面的Activity都finish掉
            FLAG_ACTIVITY_TASK_ON_HOME 这个flag将造成新任务在home的上面，就是在启动的Activity点击back之后就会回到home界面
         */
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_TASK_ON_HOME);
        context.startActivity(intent);
        context.finish();
    }

    @Override
    public void getPointsWithDrawLog(Activity activity, Integer page, Integer size, final UICallBack callBack) throws Exception {
        RequestClient.getInstance(new HttpCallBack(activity, new TypeToken<ListBean<PointsWithdrawLogBean>>() {
        }.getType()) {

            @Override
            public void onStart() {
                callBack.onStart();
            }

            @Override
            public void onCallBack(int status, Object result) {
                switch (status) {
                    case 200:
                        callBack.onRefresh(result);
                        break;
                    default:
                        callBack.onFailure(status);
                        break;
                }
            }
        }).addGetParams("page", String.valueOf(page), "size", String.valueOf(size)).excute(RequestMethod.GET, Url.POINTS_LOG);

    }

    @Override
    public void getPointsWithDraw(Activity activity, Integer page, Integer size, final UICallBack callBack) throws Exception {
        RequestClient.getInstance(new HttpCallBack(activity, new TypeToken<ListBean<PointsWithdrawBean>>() {
        }.getType()) {

            @Override
            public void onStart() {
                callBack.onStart();
            }

            @Override
            public void onCallBack(int status, Object result) {
                switch (status) {
                    case 200:
                        callBack.onRefresh(result);
                        break;
                    default:
                        callBack.onFailure(status);
                        break;
                }
            }
        }).addGetParams("page", String.valueOf(page), "size", String.valueOf(size)).excute(RequestMethod.GET, Url.POINTS_WITHDRAW);
    }

    @Override
    public void applyPointWithDraw(Activity activity, String point, final UICallBack callBack) throws Exception {
        RequestClient.getInstance(new HttpCallBack(activity, String.class) {
            @Override
            public void onStart() {
                callBack.onStart();
            }

            @Override
            public void onCallBack(int status, Object result) {
                switch (status) {
                    case 200:
                        callBack.onRefresh(result);
                        break;
                    default:
                        callBack.onFailure(status);
                        break;
                }
            }
        }).addParameter("point", point).excute(RequestMethod.POST, Url.POINTS_WITHDRAW);

    }

    @Override
    public void deleteFinishPointWithDraw(Activity activity, String withdrawId, final UICallBack callBack) throws Exception {
        RequestClient.getInstance(new HttpCallBack(activity, new TypeToken<ListBean<PointsWithdrawBean>>() {
        }.getType()) {

            @Override
            public void onStart() {
                callBack.onStart();
            }

            @Override
            public void onCallBack(int status, Object result) {
                switch (status) {
                    case 200:
                        callBack.onRefresh(result);
                        break;
                    default:
                        callBack.onFailure(status);
                        break;
                }
            }
        }).addGetParams().excute(RequestMethod.DELETE, Url.POINTS_WITHDRAW + "/" + withdrawId);
    }

    @Override
    public void confirmPointWithDraw(Activity activity, String withdrawId, final UICallBack callBack) throws Exception {
        RequestClient.getInstance(new HttpCallBack(activity, String.class) {

            @Override
            public void onStart() {
                callBack.onStart();
            }

            @Override
            public void onCallBack(int status, Object result) {
                switch (status) {
                    case 200:
                        callBack.onRefresh(result);
                        break;
                    default:
                        callBack.onFailure(status);
                        break;
                }
            }
        }).addParameter().excute(RequestMethod.POST, Url.POINTS_WITHDRAW + "/" + withdrawId + "/confirm");
    }

    @Override
    public void reportPointWithDraw(Activity activity, String withdrawId, String detail, String imageFid, String reason, final UICallBack callBack) throws Exception {
        RequestClient.getInstance(new HttpCallBack(activity, String.class) {
            @Override
            public void onStart() {
                callBack.onStart();
            }

            @Override
            public void onCallBack(int status, Object result) {
                switch (status) {
                    case 200:
                        callBack.onRefresh(result);
                        break;
                    default:
                        callBack.onFailure(status);
                        break;
                }
            }
        }).addParameter("detail", detail, "imageFid", imageFid, "reason", reason).excute(RequestMethod.POST, String.format("%s%s%s%s", Url.POINTS_WITHDRAW, "/", withdrawId, "/report"));

    }

    @Override
    public void getPointAskWithDraw(Activity activity, Integer page, Integer size, String state, final UICallBack callBack) throws Exception {
        RequestClient.getInstance(new HttpCallBack(activity, new TypeToken<ListBean<WithDrawAskBean>>() {
        }.getType()) {

            @Override
            public void onStart() {
                callBack.onStart();
            }

            @Override
            public void onCallBack(int status, Object result) {
                switch (status) {
                    case 200:
                        callBack.onRefresh(result);
                        break;
                    default:
                        callBack.onFailure(status);
                        break;
                }
            }
        }).addGetParams("page", String.valueOf(page), "size", String.valueOf(size), "state", state).excute(RequestMethod.GET, Url.ASK_WITHDRAW);
    }

    @Override
    public void deletePointAskWithDraw(Activity activity, String withdrawId, final UICallBack callBack) throws Exception {
        RequestClient.getInstance(new HttpCallBack(activity, new TypeToken<ListBean<WithDrawAskBean>>() {
        }.getType()) {

            @Override
            public void onStart() {
                callBack.onStart();
            }

            @Override
            public void onCallBack(int status, Object result) {
                switch (status) {
                    case 200:
                        callBack.onRefresh(result);
                        break;
                    default:
                        callBack.onFailure(status);
                        break;
                }
            }
        }).addGetParams().excute(RequestMethod.DELETE, Url.ASK_WITHDRAW + "/" + withdrawId);
    }

    @Override
    public void payPointAskWithDraw(Activity activity, String withdrawId, String paymentFid, final UICallBack callBack) throws Exception {
        RequestClient.getInstance(new HttpCallBack(activity, new TypeToken<ListBean<WithDrawAskBean>>() {
        }.getType()) {

            @Override
            public void onStart() {
                callBack.onStart();
            }

            @Override
            public void onCallBack(int status, Object result) {
                switch (status) {
                    case 200:
                        callBack.onRefresh(result);
                        break;
                    default:
                        callBack.onFailure(status);
                        break;
                }
            }
        }).addParameter("paymentFid", paymentFid).excute(RequestMethod.POST, Url.ASK_WITHDRAW + "/" + withdrawId + "/pay");
    }

    @Override
    public void payMorePointAskWithDraw(Activity activity, String withdrawId, String paymentFid, final UICallBack callBack) throws Exception {
        RequestClient.getInstance(new HttpCallBack(activity, new TypeToken<ListBean<WithDrawAskBean>>() {
        }.getType()) {

            @Override
            public void onStart() {
                callBack.onStart();
            }

            @Override
            public void onCallBack(int status, Object result) {
                switch (status) {
                    case 200:
                        callBack.onRefresh(result);
                        break;
                    default:
                        callBack.onFailure(status);
                        break;
                }
            }
        }).addParameter("paymentFid", paymentFid).excute(RequestMethod.POST, Url.ASK_WITHDRAW + "/" + withdrawId + "/pay-more");
    }

    private boolean isCurrentActivity(Context context) {
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        try {
            if (manager != null && manager.getRunningTasks(1) != null && manager.getRunningTasks(1).size() > 0) {
                String name = manager.getRunningTasks(1).get(0).topActivity.getClassName();
                if (StringUtil.isEquals(name, LoginActivity.class.getName()) || StringUtil.isEquals(name, ResetPasswordActivity.class.getName())) {
                    return true;
                }
            }
        } catch (SecurityException e) {
            e.printStackTrace();
        }
        return false;
    }

}
